package com.cx.controller;


import com.cx.utils.CommonTools;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

//关于图片操作
@RestController
@RequestMapping("/picture")
@CrossOrigin
public class pictureController {

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        // 输入流读取，输出流写回浏览器
        try {
            // 创建文件
            File file = new File(name);
            if (!file.exists()) {
                // 处理文件不存在的情况
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
                return;
            }

            // 确定文件类型
            String mimeType = CommonTools.getMimeType(file);
            // 设置内容类型
            response.setContentType(mimeType);

            // 使用BufferedInputStream和BufferedOutputStream进行缓冲读写
            try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file));
                 BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream())) {

                byte[] buffer = new byte[1024 * 4];
                int len;
                while ((len = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, len);
                }
                // 这里不需要手动flush和close，try-with-resources会自动关闭流
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
